import axios from "axios";
import { ElMessage } from "element-plus";

const baseURL = import.meta.env.VITE_BASE_URL;

const server = axios.create({
  // baseURL: import.meta.env.VITE_BASE_URL,
  baseURL: baseURL,
  timeout: 300000,
});

server.interceptors.request.use(
  async (config) => {
    let data = {};
    config.headers = { "Content-Type": "application/json;" };
    const token = await localStorage.getItem("token");
    if (token && token !== "undefined") {
      config.headers["token"] = JSON.parse(token);
    }
    if (config.data) {
      data = config.data;
      if (data.file) {
        config.headers = {
          "Content-Type": "multipart/form-data;",
        };
        if (token && token !== "undefined") {
          config.headers["x-token"] = JSON.parse(token);
        }
        let formData = new FormData();
        formData.append("file", data.file);
        config.data = formData;
      } else {
        config.data = JSON.stringify(data);
      }
    }
    return config;
  },
  function (err) {
    Promise.reject(err);
  }
);

server.interceptors.response.use(
  async (response) => {
    if (response.data.code == 3003) {
      ElMessage.info("登录过期");
      localStorage.removeItem("token");
      window.location.href = "/login";
    }
    return response;
  },
  (err) => {
    if (err.response.data.code == 3003) {
      ElMessage.info("登录过期");
      localStorage.removeItem("token");
      window.location.href = "/login";
    }
    return err;
  }
);

export default server;
